<?php

/**
 * @Author: CraspH2b
 * @Date:   2018-01-20 14:49:53
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-03-30 10:03:23
 */
namespace app\admin\model;
use think\Model;
use think\Validate;
use think\Request;
use think\Db;

class Admin extends Model{
	/**
	 * 判断登录
	 * @return [type] [description]
	 */
	public function login($username,$password){
        $username = trim($username);
        $password = trim($password);
        if(!$username || !$password) $this->error = '用户名或者密码不能为空!';

        //查找数据库 判断登录
        $admin_user = self::where('username',$username)->find();
        if(!$admin_user){
        	$this->error = '用户不存在!';
        	return false;
        }
        if($admin_user['status'] == '0'){
        	 $this->error = '用户名被禁用!';
        	 return false;
        }

        $password = get_password($admin_user['pwd_mix'],$password);
        if($password != $admin_user['password']){
        	$this->error = '密码错误!';
        	return false;
        } 

        //登录成功，记录更新信息
        $update_data = [
                'times' => (string)(intval($admin_user['times'])+1),
                'login_ip' => request()->ip(),
                'last_login_ip' => $admin_user['login_ip'],
                'login_time'   => (string)time(),
                'last_login_time' => $admin_user['login_time']
        ];
        //更新登录信息
        if(self::where('id',$admin_user['id'])->update($update_data)){
             //生成签名，保存cookie和session
             $signature_data = [
                      'id'  => (string)$admin_user['id'],
                      'username'=> $admin_user['username'],
                      'avatar'  => $admin_user['avatar'],
                      'tel'      => $admin_user['tel'],
                      'email'      => $admin_user['email'],
             ];
             $signature_data_merge = array_merge($signature_data,$update_data);
             $signature = get_signature($signature_data_merge);
             session('admin_user',$signature_data_merge);
             session('admin_user_sig',$signature);
             cookie('admin_user',$signature_data_merge,3600*2);
             cookie('admin_user_sig',$signature,3600*2);
             return true;
        }
	}
	/**
	 * 判断是否登录
	 * @return boolean [description]
	 */
	public function is_login(){
       if(session('admin_user')){
       	   $admin_user = session('admin_user');
       	   $admin_user_sig = session('admin_user_sig');
       	   //验证签名
       	   if(check_signature($admin_user,$admin_user_sig)){
       	   	   return true;
       	   }else{
       	   	   return false;
       	   }
       }else{
       	  if(cookie('admin_user')){
              $admin_user = cookie('admin_user');
       	      $admin_user_sig = cookie('admin_user_sig');
       	      if(check_signature($admin_user,$admin_user_sig)){
       	      	    session('admin_user',$admin_user);
                    session('admin_user_sig',$admin_user_sig);
       	   	   	   return true;
	       	   }else{
	       	   	   return false;
	       	   }
       	  }else{
       	  	  return false;
       	  }
       }
	}
  /**
   * 添加管理员
   * @return [type] [description]
   */
  public function admin_add($data){
      $rule = [
          'username'  => 'require|alphaNum|token|unique:admin',
          'tel'   => 'number|length:11',
          'email' => 'email',
      ];

      $msg = [
          'username.require' => '用户名不能为空',
          'username.token' => '表单不能重复提交',
          'username.alphaNum'     => '用户只能是字母或者数字组成',
          'username.unique'   => '用户已存在',
          'tel.number'  => '电话必须是数字',
          'tel.length'  => '电话只能是11位',
          'email'        => '邮箱格式不正确',
      ];
     //生成密码
      $data['pwd_mix'] = get_mix();
      $group_id = $data['group_id'];
      unset($data['group_id']);
      $data['password'] = get_password($data['pwd_mix'],$data['password']);
      $validate = new Validate($rule, $msg);
      $result   = $validate->check($data);
      if($result){
         $data['pwd_mix'] = get_mix();
         $data['password'] = get_password($data['pwd_mix'],$data['password']);
         $data['addtime'] = time();
         unset($data['__token__']);
         if(self::save($data)){
             $group_data = [
                     'uid' => $this->id,
                     'group_id' => $group_id,
                  ];
              Db::name('auth_group_access')->insert($group_data);
            return true;
         }else{
            $this->error = "添加管理员失败";
            return false;
         }
      }else{
         $this->error = $validate->getError();
         $this->data = Request::instance()->token();
         return false;
      }
  }
  /**
   * 用户修改
   * @param  [type] $data [description]
   * @return [type]       [description]
   */
  public function admin_edit($data){
     //修改的情况
     //  1：超级管理员并且id为1的可以修改所有的
     //  2：其他超级管理员只能修改自己跟其他的
     //  3：普通的只能修改自己的
     $admin_id = session('admin_user.id');
     if($admin_id != 1){
        $group_id = Db::name('auth_group_access')->where('uid',$admin_id)->value('group_id');
        //修改的group_id
        $group_id_edit = Db::name('auth_group_access')->where('uid',$data['id'])->value('group_id');
        if($group_id == 1){
             //超级管理员修改其他超级管理员 不允许
            if($group_id_edit == 1 && $admin_id != $data['id']){
                $this->error = "没有修改权限";
                return false;                
            } 
        }else{
          //普通管理员修改其他的用户  不允许
            if($admin_id != $data['id']){
                $this->error = "没有修改权限";
                return false;                
            }
        }
     }
     if($this->where(['id'=>['neq',$data['id']],'username'=>$data['username']])->find()){
         $this->error = "用户名已存在";
         return false;
     }
     if($data['password']){
         $data['pwd_mix'] = get_mix();
         $data['password'] = get_password($data['pwd_mix'],$data['password']);
     }else{
        unset($data['password']);
     }
     if(!isset($data['status'])){
        $data['status'] = '0';
     }
     $group_id = isset($data['group_id'])?$data['group_id']:'';
     unset($data['group_id']);
     if(self::update($data)){
        if($group_id){
           Db::name('auth_group_access')->where('uid',$data['id'])->setField('group_id',$group_id);
        }
         return true;
     }else{
         $this->error = "修改管理员失败";
         return false;
      }
  }
  /**
   * 更新管理员状态
   * @param  [type] $id [管理员id]
   * @return [type]     [description]
   */
  public function admin_status($id){
      //修改的情况
     //  1：超级管理员并且id为1的可以修改所有的
     //  2：其他超级管理员只能修改自己跟其他的
     //  3：普通的只能修改自己的
     $admin_id = session('admin_user.id');
     if($admin_id != 1){
        $group_id = Db::name('auth_group_access')->where('uid',$admin_id)->value('group_id');
        //修改的group_id
        $group_id_edit = Db::name('auth_group_access')->where('uid',$id)->value('group_id');
        if($group_id == 1){
             //超级管理员修改其他超级管理员 不允许
            if($group_id_edit == 1 && $admin_id != $id){
                $res = ['code'=>'0','msg'=>'没有修改权限'];  
                return $res;          
            } 
        }else{
          //普通管理员修改其他的用户  不允许
            if($admin_id != $id){
                $res = ['code'=>'0','msg'=>'没有修改权限'];   
                return $res;          
            }
        }
     }
      $status = $this->where('id',$id)->value('status');
      $res = [];
      if($status == '1'){
        if($this->where('id',$id)->setField('status','0')){
          $res = ['code'=>'1','msg'=>'已禁用','btn'=>'0'];
        }else{
          $res = ['code'=>'0','msg'=>'修改失败'];
        }
      }else{
          if($this->where('id',$id)->setField('status','1')){
          $res = ['code'=>'1','msg'=>'已开启','btn'=>'1'];
        }else{
          $res = ['code'=>'0','msg'=>'修改失败'];
        }
      }
      return $res;
  }
} 